package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.UserLoginBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/2/18 14:31
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(
            3004,
            2,
            "Dws_04_DwsUserUserLoginWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
        
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                    .withIdleness(Duration.ofSeconds(60))
            )
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject obj) throws Exception {
                    String uid = obj.getJSONObject("common").getString("uid");
                    String lastPageId = obj.getJSONObject("page").getString("last_page_id");
                    return uid != null && ("login".equals(lastPageId) || lastPageId == null);
                }
            })
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
            
                private ValueState<String> lastLoginDateState;
            
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDate", String.class));
                }
            
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    Long ts = value.getLong("ts");
                
                    String today = AtguiguUtil.tsToDate(ts);
                
                    String lastLoginDate = lastLoginDateState.value();
                    Long uuCt = 0L;
                    Long backCt = 0L;
                    // 今天的第一次登录记录
                    if (!today.equals(lastLoginDate)) { // 这个用户的今天第一次登录
                        uuCt = 1L;
                        lastLoginDateState.update(today);
                        // 这个用户是否是回流用户? 曾经登陆过, 最后一次登录日期和今天相差 7 天以上
                        if (lastLoginDate != null) {
                            Long lastLoginTs = AtguiguUtil.dateToTs(lastLoginDate);
                            Long todayTs = AtguiguUtil.dateToTs(today);
                            if ((todayTs - lastLoginTs) / 1000 / 60 / 60 / 24 > 7) {
                                backCt = 1L;
                            }
                        }
                    }
                
                    if (uuCt == 1) {
                        out.collect(new UserLoginBean(
                            "", "",
                            backCt, uuCt,
                            ts
                        ));
                    }
                
                }
            })
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean value1,
                                                UserLoginBean value2) throws Exception {
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                        return value1;
                    }
                },
                new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<UserLoginBean> values,
                                      Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean bean = values.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(window.getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(window.getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            )
            .addSink(FlinkSinUtil.getClickHouseSink("dws_user_user_login_window", UserLoginBean.class));
    
    }
}
/*
用户域用户登录各窗口
    当日独立用户数
    

    统计七日回流用户和
    
1. 过滤登陆记录
    两种登陆:
        自动登陆
            last_page_id = null && uid != null
        
        访问到某个页面的时候, 跳转到登录页面, 然后实现登录,再调整之前的页面
            A -> login -> A(√)
            last_page_id = login && uid != null
            
            合并:
            
            (last_page_id = login || null) && uid != null
        

2. 这个用户的当天的第一条登陆记录
    
    使用状态
    七日回流用户
        如果是用户今天第一次登录
            今天和最后一次登录的日期 差值是否大于 7
            
3.
 
 */
